package com.tbabs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbabs.common.CustomException;
import com.tbabs.entity.Category;
import com.tbabs.entity.Dish;
import com.tbabs.entity.Setmeal;
import com.tbabs.mapper.CategoryMapper;
import com.tbabs.service.CategoryService;
import com.tbabs.service.DishService;
import com.tbabs.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前对比是否与菜品或套餐关联
     * @param id 分类id
     */
    @Override
    public void removeByCnd(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        long dCount = dishService.count(dishLambdaQueryWrapper);

        if (dCount > 0) {
            // 抛出业务异常
            throw new CustomException("当前分类关联了菜品，无法删除！");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        long sCount = setmealService.count(setmealLambdaQueryWrapper);

        if (sCount > 0) {
            // 抛出业务异常
            throw new CustomException("当前分类关联了套餐，无法删除！");
        }

        // 业务正常，正常删除
        super.removeById(id);
    }
}
